package com.whq.knowverywell.adapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.whq.knowverywell.R;
import com.whq.knowverywell.business.model.HomeItem;
import com.whq.knowverywell.util.LogUtil;

public class HomeAdapter extends BaseAdapter {
	private static final String TAG = HomeAdapter.class.getSimpleName();
	
	private List<HomeItem> itemsList;
	private LayoutInflater inflater;
	private Activity ctx;
	
	public HomeAdapter(Activity ctx, List<HomeItem> itemsList) {
		this.itemsList = itemsList;
		this.ctx = ctx;
		this.inflater = LayoutInflater.from(ctx);
		
		if (this.itemsList == null) {
			this.itemsList = new ArrayList<HomeItem>();
		}
	}

	@Override
	public int getCount() {
		return itemsList.size();
	}

	@Override
	public HomeItem getItem(int position) {
		return itemsList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// init view
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.home_item, null);
			viewHolder = new ViewHolder();
			viewHolder.itemImageView = (ImageView) convertView.findViewById(R.id.item_imageView);
			viewHolder.itemTitleTextView = (TextView) convertView.findViewById(R.id.item_title_textview);
			
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		// set value of view
		HomeItem item = getItem(position);
		if (item == null) {
			return convertView;
		}
		LogUtil.i(TAG, "the " + position + " position of list is " + item.toString() );
		
		viewHolder.itemImageView.setBackgroundResource(item.getResourceId());
		viewHolder.itemTitleTextView.setText(item.getItemTitle());
		
		return convertView;
	}
	
	class ViewHolder {
		ImageView itemImageView;
		TextView itemTitleTextView;
	}

}
